angular.module('faApp')
.directive('scrollIf', function () {
	return function (scope, element, attributes) {
		setTimeout(function () {
			if (scope.$eval(attributes.scrollIf)) {
				var h = (new Date()).getHours();
				element[0].parentElement.scrollTop = h * 50;
			}
		});
	}
})
.directive("passwordVerify", function() {
   return {
      require: "ngModel",
      scope: {
        passwordVerify: '='
      },
      link: function(scope, element, attrs, ctrl) {
        scope.$watch(function() {
            var combined;

            if (scope.passwordVerify || ctrl.$viewValue) {
               combined = scope.passwordVerify + '_' + ctrl.$viewValue; 
            }                    
            return combined;
        }, function(value) {
            if (value) {
                ctrl.$parsers.unshift(function(viewValue) {
                    var origin = scope.passwordVerify;
                    if (origin !== viewValue) {
                        ctrl.$setValidity("passwordVerify", false);
                        return undefined;
                    } else {
                        ctrl.$setValidity("passwordVerify", true);
                        return viewValue;
                    }
                });
            }
        });
     }
   };
}) 
.directive("loadScript", ["$timeout",  function ($timeout ) {
	return {
		replace: true,
		restrict: 'AE',
		link: function (scope, elm, iAttrs) {

			var callBack = scope.$eval(iAttrs.callBack);
			var async = iAttrs.async === false;

			iAttrs.$observe("src", function (src) {
				if (src) {
					scriptTag(scope.$eval(src), function () {
						$timeout(function () {
							callBack && callBack();
						})
					}, async);
				}
			});


			function scriptTag(src, callback, async) {
				var doc = document,
					head = document.getElementsByName("head")[0],
					s = doc.createElement('script');

				s.type = 'text/' + (src.type || 'javascript');
				s.src = src.src || src;
				s.async = async || true;

				s.onreadystatechange = s.onload = function () {

					var state = s.readyState;

					if (!state || /loaded|complete/.test(state)) {
						callback(arguments);
					}
				};

				// use body if available. more safe in IE
				(doc.body || head).appendChild(s);
			};
		}
	};
}])

.directive("navMenu", function() {
  return {
    link: function(scope, element, attrs, ctrl) {
      attrs['module'] = attrs['module'] || "";
    
      scope.$watch('nav', function() {
        if (scope.nav.module == attrs['module']){
          element.removeClass("ng-hide");
        }else{
          element.addClass("ng-hide");
        }
      },true);
    }
  };
})  
.directive("hasAuth", ['sessionService','ajaxService','authService',function(sessionService,ajaxService,authService) {
  return {
    priority:100,
    link: function(scope, element, attrs, ctrl) {
      var who = attrs.who || "",
          where = attrs.where || "";
          owner = attrs.owner || "";
      
      // 权限
      scope._access = sessionService.getItem("user.access","");
      if (scope._access == "all")return;
      try{
        scope.user = angular.fromJson(sessionService.getItem("user",""));
      }catch(ex){
        scope.user = {};
      }
      

      var btnProcess = function(){
        var authFlag = false;
        angular.forEach(who.split(","),function(o){
          var realUrl = ajaxService.getApiUri(o);
          urlPaths = realUrl.split("/"),
          lastUrlPath = urlPaths[urlPaths.length - 1];
        if (scope._access.indexOf(lastUrlPath) != -1){
          authFlag = true 
        }
        });

        var ownerFlag = false;
        if (authFlag){
          if (!owner)ownerFlag = true;
          else{
            if (owner == scope.user.name){
              ownerFlag = true;
            }
          }
        }


        if (!(authFlag && ownerFlag)){
          element.remove();
        }
      };
      
      var topProcess = function(){
      
        var groups = [];
        angular.forEach(scope._access.split(","),function(o){
          var m = authService.getModule(o);
          if (groups.indexOf(m) == -1){
            groups.push(m);
          }    
        });
        if (groups.indexOf(who) == -1){
          element.remove();
        }
      };
      
      var roleProcess = function(){
        var authFlag = false;
        if (who == "PRODUCT_CORE_PRICE"){
        
        }
      
        if (!authFlag){
          element.remove();
        }
      };
      
      if (attrs.owner == undefined){
        if (where == "top"){
          topProcess();
        }else if (where == "btn"){
          btnProcess();
        }else if (where == "role"){
          roleProcess();
        }
      }else{
        attrs.$observe('owner',function(v){
          owner = attrs.owner;
          if (owner){
            if (where == "top"){
              topProcess();
            }else if (where == "btn"){
              btnProcess();
            }else if (where == "role"){
              roleProcess();
            }
          }
        }); 
      }
    }
  };
}]) 
.directive('ngConfirmClick', [
  function(){
    return {
      priority: 1,
      terminal: true,
      restrict: 'A',
      link: function(scope, element, attrs){
        element.bind('click', function(e){
          var message = attrs.ngConfirmClick || "请确认操作";
          if(confirm(message)){
            scope.$eval(attrs.ngClick)
          }else{
            e.stopImmediatePropagation();
            e.preventDefault();
          }
        });
      }
    }
  }
])
.directive('onlyNum', function() {
      return function(scope, element, attrs) {

          element.bind("keypress", function(event) {
            event = (event) ? event : ((window.event) ? window.event : ""); 
            var k = event.keyCode?event.keyCode:event.which;
            if(!((k>=48 && k<= 57) || (k==8) || (k==46))) {
                scope.$apply(function(){
                    scope.$eval(attrs.onlyNum);
                    event.preventDefault();
                });
                event.preventDefault();
            }

        });
     };
  })
.directive('nameInput', function() {//only [0-9],[a-z],[A-Z],中文
      return function(scope, element, attrs) {

          element.bind("keypress", function(event) {
            event = (event) ? event : ((window.event) ? window.event : ""); 
            var k = event.keyCode?event.keyCode:event.which;
            if(!((k>=97 && k<=122) || (k>=65 && k<=90) || (k>=48 && k<= 57) || (k==8))) {
                scope.$apply(function(){
                    scope.$eval(attrs.onlyNum);
                    event.preventDefault();
                });
                event.preventDefault();
            }

        });
     };
  })
.directive('clickAnywhereButHere', function($document){
  return {
    restrict: 'A',
    link: function(scope, elem, attr, ctrl) {
      elem.bind('click', function(e) {
        e.stopPropagation();
      });
      $document.bind('click', function() {
        scope.$apply(attr.clickAnywhereButHere);
      })
    }
  }
})
.directive('eChart', function ($location) {
    function link($scope, element, attrs) {
        var myChart = echarts.init(element[0]);
        $scope.$watch(attrs['eData'], function () {
            var option = $scope.$eval(attrs.eData);
            if (angular.isObject(option)) {
                myChart.setOption(option);

                if(attrs['eEvent'] == 'true'){
                    console.log(attrs['eEvent']);
                    myChart.on('click', function (params) {
                        if(params.name.split(',,,')[0]){
                            window.location = '/fa/view?id=' + params.name.split(',,,')[0];
                        }
                    });
                }
            }
        }, true);
        $scope.getDom = function () {
            return {
                'height': element[0].offsetHeight,
                'width': element[0].offsetWidth
            };
        };
        $scope.$watch($scope.getDom, function () {
            // resize echarts图表
            myChart.resize();
        }, true);
    }
    return {
        restrict: 'A',
        link: link
    };
})
.directive('a', function($document, $timeout){
    return {
        restrict: 'E',
        link: function(scope, elem, attr, ctrl) {
            if(attr.href && attr.href.indexOf('?') > 0){
                $timeout(function(){
                    var param = attr.href.split('?');
                    param[1] = 'token=' + App.randomString(100) + '&' + param[1] + '&' + App.randomString(60);

                    var tmp = param[0] + '?' + param[1];
                    attr.$set('href', tmp);
                }, 50);
            }
        }
    }
})
;

